// 封装axios
import axios from "axios";
import { getToken } from "./token";
// const baseURL = process.env.VITE_BASE_URL
// const apiUrl=process.env.REACT_APP_API_URL
// console.log(apiUrl,'环境变量')
const http = axios.create({
  // baseURL:"http://geek.itheima.net/v1_0",
  baseURL: "http://localhost:3000",
  // baseURL:apiUrl,
  withCredentials: true,
  timeout: 5000, // 超时时间定下5秒钟
  headers:{
    'Content-Type': 'application/json',//设置默认请求头
  }
})
// 添加请求拦截器
http.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem('accessToken')
  if (accessToken) {
    config.headers.Authorization = accessToken
    // config.headers['token'] = token
  }
  console.log(config.headers);
  

  return config
}, (error) => {
  return Promise.reject(error)
})
// 添加响应拦截器
http.interceptors.response.use((response) => {
  // 2xx 范围内的状态码都会触发该函数
  console.log(response, '响应数据')
  return response.data
}, async error => {

  const originalRequest = error.config
  if (error.response.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true
    try {
      localStorage.setItem('accessToken', error.response.data.accessToken)
      localStorage.setItem('refreshToken', error.response.data.refreshToken)

      originalRequest.headers.Authorization = error.response.data.accessToken
      originalRequest.headers.pass = error.response.data.refreshToken
      return $http(originalRequest)
    } catch (error) {
      return Promise.reject(error)
    };
  }
  console.log(error);
  window.location.href = '/loginCode'

  return Promise.reject(error);
})

export default http